package com.newsmanagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.newsmanagement.domain.pojo.WholBatch;
import com.newsmanagement.mapper.WholBatchMapper;
import com.newsmanagement.service.WholBatchService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author adim
 * @description 针对表【whol_batch(批发商产品批号信息表)】的数据库操作Service实现
 * @createDate 2025-10-11 15:17:30
 */
@Service
public class WholBatchServiceImpl extends ServiceImpl<WholBatchMapper, WholBatch>
        implements WholBatchService {

    @Override
    public boolean checkBatchIdExists(String batchId) {
        LambdaQueryWrapper<WholBatch> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WholBatch::getBatchId, batchId);
        return baseMapper.exists(queryWrapper);
    }

    @Override
    public boolean addWholBatch(WholBatch wholBatch) {
        // 检查批号是否已存在
        if (checkBatchIdExists(wholBatch.getBatchId())) {
            return false;
        }
        // 设置默认状态为"新建"
        wholBatch.setState(1);
        // 设置屠宰企业批号ID
        wholBatch.setSbId(wholBatch.getSlauBatchId());
        return save(wholBatch);
    }

    @Override
    public List<WholBatch> getByState(Integer state) {
        LambdaQueryWrapper<WholBatch> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WholBatch::getState, state);
        return baseMapper.selectList(queryWrapper);
    }

    // 分页查询实现
    @Override
    public IPage<WholBatch> pageQuery(Page<WholBatch> page, Integer wholId, Integer state, String type) {
        LambdaQueryWrapper<WholBatch> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(wholId != null, WholBatch::getWholId, wholId)
                .eq(state != null, WholBatch::getState, state)
                .like(type != null, WholBatch::getType, type)
                .orderByDesc(WholBatch::getBatchDate); // 按时间倒序
        return baseMapper.selectPage(page, queryWrapper);
    }

    // 根据批发商ID查询
    @Override
    public List<WholBatch> getByWholId(Integer wholId) {
        LambdaQueryWrapper<WholBatch> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WholBatch::getWholId, wholId)
                .orderByDesc(WholBatch::getBatchDate);
        return baseMapper.selectList(queryWrapper);
    }
    
    // 根据批发商ID和状态查询
    public List<WholBatch> getByWholIdAndState(Integer wholId, Integer state) {
        LambdaQueryWrapper<WholBatch> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WholBatch::getWholId, wholId)
                .eq(WholBatch::getState, state)
                .orderByDesc(WholBatch::getBatchDate);
        return baseMapper.selectList(queryWrapper);
    }
}